package com.bdqn.t362.user.servlet;

import com.aliyuncs.utils.StringUtils;
import com.bdqn.t362.common.utils.OSSUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

/**
 * @author lqm
 * @ClassName ${NAME}
 * @description: 将文件上传到服服务器
 */
@WebServlet("/UploadServlet")
//注意需要添加该注解，让servlet支持文件上传
@MultipartConfig
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        String result = "";
        try {
            //获取表单提交的文件流
            Part part = request.getPart("userImg");

            //获取服务器存放文件的地址
            String pathStr = request.getSession().getServletContext()
                    .getRealPath("upload");

            File file = new File(pathStr);
            if (!file.exists()) {
                file.mkdirs();
            }
            //需要获取文件名  需要知道文件的后缀
//        String contentDis = part.getHeader("content-disposition");
//        System.out.println("contentDis=" + contentDis);
//        String[] contentArr = contentDis.split(";");
//        String fileName = "";
//        for (String tempStr : contentArr) {
//            //filename="AA83389CA26D89BCB4E50524347E18CF.png"
//            if (tempStr.trim().startsWith("filename")) {
//                fileName = tempStr.substring(tempStr.indexOf("=") + 2, tempStr.length() - 1);
//            }
//        }

            //存储到本地 该方法tomcat8之后才可用
            String fileName = part.getSubmittedFileName();
            //将提交的文件保存到savePath路径
            String savePath = pathStr + File.separator + fileName;
            part.write(savePath);

            result="upload" + File.separator + fileName;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
        //如果为空则上传失败
        if (!StringUtils.isEmpty(result)) {
            request.setAttribute("imgSrc", result);
        } else {
            request.setAttribute("errorMsg", "上传文件失败！");
        }
        request.getRequestDispatcher("index.jsp").forward(request, response);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
